import { message , Divider,Modal, Space, Button, Card } from 'antd';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { ExclamationCircleOutlined,PlusOutlined } from '@ant-design/icons';

import React, { useState, useRef } from 'react';
import styles from '../style.less'
import { queryDeviceLinkage, updateDeviceLinkage, addDeviceLinkage, removeDeviceLinkage ,batchRemoveDeviceLinkage} from '@/services/deviceLinkage';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { Link,history } from 'umi';
const { confirm } = Modal;


/**
 * 添加节点
 * @param fields
 */
 const handleAdd = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在添加');
  try {
    var id= await addDeviceLinkage(fields);
    hide();
    resetForm();
    message.success('添加成功');
    return id;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return null;
  }
};


/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceLinkage(fields);
    hide();
    resetForm();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (fields: any) => {
  const hide = message.loading('正在删除');

  try {
    await removeDeviceLinkage();
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const Configure: React.FC = () => {
  const [formValues, setFormValues] = useState({});
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);

  };
  
  //批量删除
  const batchRemove = async () => {
    const hide = message.loading('正在删除');
    try {
      await batchRemoveDeviceLinkage({ ids: selectedRowKeys.join(',')});
      setSelectedRowKeys([]);
      hide();
      message.success('删除成功，正在刷新！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

   type TableListItem = {
    ID: number;
    task: string;
    condition: string;
    result: string;
  };
  const dataSource : TableListItem[] = [];
  for (let i = 0; i < 2; i += 1) {
    dataSource.push( {
      ID: i ,
      task:'联动任务',
      condition: '联动条件',
      result: '联动结果',
    })

  }


  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'index',
      search:false,
    },
    {
      title: '联动任务',
      dataIndex: 'name',
      valueType: 'string',
      render: (_,record) => 
      <Link to={{pathname:`/linkage/details/${record.id}`,state:{linkageInfo:record}}} >  {_}</Link>
    }, 
    {
      title: '是否暂停',
      valueType: 'radio',
      dataIndex: 'isSuspend',
      valueEnum: {
        0:  '否' ,
        1: '是',
      }
    },   
    {
      title: '暂停截止时间',
      dataIndex: 'suspendTime',
      valueType: 'string',
      search:false,
    },
    {title: '是否启用',
    dataIndex: 'useState',
    valueType: 'radio',
    valueEnum: {
      0:  '未启用' ,
      1: '已启用',
    }
    },
     {
      title: '操作',
      key: 'ID',
      search:false,
      valueType: 'option',
      render: (_, record) => (
        <>
        <a
          key="editable"
          onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        > 编辑</a><Divider type="vertical" /> <Link to={{pathname:`/linkage/details/${record.id}`,state:{linkageInfo:record}}} >详情</Link>
          <Divider type="vertical" />
              <a onClick={() => {
                confirm({
                  title: '您确定要删除吗?',
                  icon: <ExclamationCircleOutlined />,
                  async onOk() {
                    await removeDeviceLinkage({id:record.id});
                    actionRef?.current?.reload();
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }}
              >删除</a>
         </>
     )
    },
  ];




    return (
      <div className={styles.linkage}>
          <ProTable<TableListItem>
            toolBarRender={(action, { selectedRows }) => [
              <Button icon={<PlusOutlined />} className={styles.addBtn}  type="primary" onClick={() => handleModalVisible(true)}>
                新增
              </Button>
            ]}
          columns={columns}
          actionRef={actionRef}
          // search={false}
          rowSelection={{selectedRowKeys,onChange: onSelectChange}}
          tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          )}
          tableAlertOptionRender={() => {
            return (
              <Space size={16}>
                <a  onClick={() => {
                confirm({
                  title: '您确定要批量删除吗?',
                  icon: <ExclamationCircleOutlined />,
                  async onOk() {
                    await batchRemove();
                    actionRef.current?.reload();
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }} >批量删除</a>
             
              </Space>
            );
          }}
          options={false}
          request={(params) => queryDeviceLinkage(params)}
          pagination={{
            defaultCurrent: 1,
            defaultPageSize: 20,
          }}
          rowKey="id" />
      
       
        <CreateForm
        onSubmit={async (value,resetForm) => {
          const id = await handleAdd(value,resetForm);
          if (id!=null) {
            handleModalVisible(false);
            history.push({
              pathname: `/linkage/details/${id}`,
              state: { linkageInfo: value }
            });
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      />
    
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value,resetForm) => {
            const success = await handleUpdate(value,resetForm);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
        />
      ) : null}
  </div>
    );
};

export default Configure;